<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.company_id ? '公司资料' : '添加公司资料'" v-model="visible" align-center width="1200px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <div class="grid grid-cols-4 gap-x-3">
        <el-form-item label="资料来源" prop="source" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.source" :options="options.source" class="w-full" placeholder="请选择" />
        </el-form-item>
        <el-form-item label="公司名称" prop="company_name_ch" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model.lazy="form.company_name_ch" placeholder="请输入" :maxlength="200" @change="val => pinyin(val, 'company_name_py')" />
        </el-form-item>
        <el-form-item label="公司名称拼音" prop="company_name_py" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]" class="col-span-2">
          <el-input v-model.lazy="form.company_name_py" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="营业执照号" prop="license_num" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model.lazy="form.license_num" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="公司成立时间" prop="established_date" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-date-picker v-model="form.established_date" placeholder="日期选择" type="date" value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
        <el-form-item v-if="form.company_address_type === 1" label="公司地址" prop="company_area_id" class="col-span-2 contain-fix"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <div class="flex w-full">
            <VSelect v-model="form.company_address_type" :options="options.company_address_type" placeholder="请选择" :clearable="false" select style="flex: 0 0 80px" />
            <Area v-model="form" field="company" level="4" required @change="val => pinyin(val, 'company_address_pinyin')" />
          </div>
        </el-form-item>
        <el-form-item v-else label="公司地址" prop="company_address_detail" class="col-span-2 contain-fix" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <div class="flex w-full">
            <VSelect v-model="form.company_address_type" :options="options.company_address_type" placeholder="请选择" :clearable="false" select style="flex: 0 0 80px" />
            <el-input v-model="form.company_address_detail" placeholder="详细地址" @change="val => pinyin(val, 'company_address_pinyin')" />
          </div>
        </el-form-item>
        <el-form-item label="公司地址拼音" prop="company_address_pinyin" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]" class="col-span-3">
          <el-input v-model="form.company_address_pinyin" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="公司类型" prop="company_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.company_type" :options="options.company_type" class="w-full" placeholder="公司类型" />
        </el-form-item>
        <el-form-item label="邮编">
          <el-input v-model="form.postal_code" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="法人姓名" prop="legal_person_name" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input v-model.lazy="form.legal_person_name" @change="val => pinyin(val, 'legal_person_pinyin')" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="法人拼音" prop="legal_person_pinyin" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input v-model="form.legal_person_pinyin" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="法人身份证号" prop="legal_person_idcard" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input v-model.lazy="form.legal_person_idcard" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="身份证有效期开始日期" prop="legal_person_idcard_expire_start" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-date-picker v-model="form.legal_person_idcard_expire_start" placeholder="请选择" type="date" value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
        <el-form-item label="身份证有效期结束日期">
          <div class="flex items-center">
            <el-date-picker v-model="form.legal_person_idcard_expire_end" placeholder="长期有效" type="date" value-format="YYYY-MM-DD"
              :disabled-date="val => val.getTime() < Date.now()" class="w-full" />
            <el-button link type="primary" :disabled="!form.legal_person_idcard_expire_start" @click="setYear(10)">10年</el-button>
            <el-button link type="primary" :disabled="!form.legal_person_idcard_expire_start" class="ml-1" @click="setYear(20)">20年</el-button>
          </div>
        </el-form-item>
        <div class="grid grid-cols-3 gap-x-3 col-span-2">
          <el-form-item label="法人手机号" prop="legal_person_mobile">
            <el-input v-model.lazy="form.legal_person_mobile" placeholder="请输入" :maxlength="200" />
          </el-form-item>
          <el-form-item label="注册资本金" prop="registered_capital">
            <VGroup class="w-full">
              <el-input-number v-model="form.registered_capital" :controls="false" :min="0" :step="0.01" :precision="2" placeholder="请输入" class="w-full" />
              <div class="v-group-item">万</div>
            </VGroup>
          </el-form-item>
          <el-form-item label="监事" prop="supervisor">
            <el-input v-model.lazy="form.supervisor" placeholder="请输入" :maxlength="200" />
          </el-form-item>
        </div>
        <el-form-item label="" class="col-span-4" prop="business_license_photo" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VUpload v-model="form.business_license_photo" required title="营业执照图片" edit :types="['jpg', 'png', 'jpeg', 'gif', 'pdf']" />
        </el-form-item>
        <el-form-item label="" class="col-span-4" prop="legal_person_idcard_front" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VUploadFile v-model="form.legal_person_idcard_front" required title="法人身份证（正面）" edit :types="['jpg', 'png', 'jpeg', 'gif', 'pdf']" />
        </el-form-item>
        <el-form-item label="" class="col-span-4" prop="legal_person_idcard_back" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VUploadFile v-model="form.legal_person_idcard_back" required title="法人身份证（反面）" edit :types="['jpg', 'png', 'jpeg', 'gif', 'pdf']" />
        </el-form-item>
        <el-form-item label="对公银行">
          <el-input v-model="form.public_bank" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="支行">
          <el-input v-model="form.bank_branch" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model="form.bank_account_num" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="(d, i) in options.status" :key="i" :label="d.value">{{ d.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="已注册" class="col-span-full">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="form.registereds" @change="handleCheckedChange">
            <el-checkbox v-for="(d, i) in options.registered" :key="i" :label="d.value">{{ d.label }}</el-checkbox>
            <el-checkbox :label="'other'">其他</el-checkbox>
            <el-input v-if="form.registereds && form.registereds.includes('other')" v-model="form.registereds_other" class="absolute ml-2 inline-block w-80" placeholder="请输入" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入" :maxlength="800" show-word-limit />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import Area from '@/components/Area'
import ImageUpload from '@/components/ImageUpload'
import XEUtils from 'xe-utils'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const success = ref(false)
let loadings = reactive({})

const checkAll = ref(false)
const isIndeterminate = ref(false)

const handleCheckAllChange = (val) => {
  form.value.registereds = val ? props.options.registered.map(d => d.value) : []
  isIndeterminate.value = false
}
const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === props.options.registered.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.options.registered.length
}

// 表单处理
const formRef = ref()
const form = ref({})

// 设置身份证日期
const setYear = (num = 0) => {
  form.value.legal_person_idcard_expire_end = XEUtils.toDateString(XEUtils.getWhatYear(form.value.legal_person_idcard_expire_start, num), 'yyyy-MM-dd')
}

const pinyin = (convert_string, field) => {
  // api.pinyin({ convert_string }).then(res => {
  //   form.value[field] = res.data
  // })
}

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  // 编辑
  if (id) {
    const res = await api.detail({ company_id: id })
    form.value = res.data
    handleCheckedChange(form.value.registereds)
  } else { //新增
    form.value = {
      company_address_type: 1,
      "source": '',
      "company_name_ch": "",
      "company_name_py": "",
      "license_num": "",
      "established_date": "",
      "company_area_ids": [],
      "company_area_names": "",
      "company_address_detail": "",
      "company_address_pinyin": "",
      "postal_code": "",
      "business_license_photo": [],
      "legal_person_name": "",
      "legal_person_idcard": "",
      "legal_person_idcard_expire": [,],
      "legal_person_mobile": "",
      "legal_person_idcard_front": [],
      "legal_person_idcard_back": [],
      "public_bank": "",
      "bank_branch": "",
      "bank_account_num": "",
      "registereds": [],
      "status": 1,
      "remark": "",
      "create_user": ""
    }
    formRef?.value?.resetFields()
  }
  loadings = reactive({})
  success.value = false
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  api[form.value.company_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    success.value = true
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>